import { Button, DatePicker, Form, Input, Select } from "antd";
import lunisolar from "lunisolar";
import React, { useRef, useState } from "react";
import { useFiveElements } from "./hooks/useFiveElements";
import { personalityMapping } from "./hooks/useMapping";
import { useZodiac } from "./hooks/useZodiac";
import { Info } from "./type";
const { Option } = Select;

const App: React.FC = () => {
  const getElementMapping = useFiveElements();
  const [submittedData, setSubmittedData] = useState<any>(null);
  const [dataSet, setDataSet] = useState<Info>();

  const stateRef = useRef();
  stateRef.current = submittedData;

  const calcData = (stateRef: any) => {
    const fiveElement =
      stateRef.current.tianGan +
      stateRef.current.fiveElements +
      stateRef.current.gender;

    const res = personalityMapping[fiveElement];

    setDataSet(res);

    return res;
  };

  const handleSubmit = async (values: any) => {
    await setSubmittedData({
      ...values,
      // eslint-disable-next-line react-hooks/rules-of-hooks
      zodiac: useZodiac(values.birthdate.toDate()),
      fiveElements: getElementMapping(
        lunisolar(new Date(values.birthdate)).char8.day.toString()[0]
      ),
      tianGan: lunisolar(new Date(values.birthdate)).char8.day.toString()[0],
    });
    await calcData(stateRef);
  };

  return (
    <div style={{ padding: "20px" }}>
      <h1>五行生肖计算器</h1>
      <Form onFinish={handleSubmit} layout="vertical">
        <Form.Item
          label="姓名"
          name="name"
          rules={[{ required: true, message: "请输入姓名" }]}
        >
          <Input placeholder="请输入你的姓名" />
        </Form.Item>
        <Form.Item
          label="性别"
          name="gender"
          rules={[{ required: true, message: "请选择性别" }]}
        >
          <Select placeholder="请选择你的性别">
            <Option value="男">男</Option>
            <Option value="女">女</Option>
          </Select>
        </Form.Item>
        <Form.Item
          label="出生日期"
          name="birthdate"
          rules={[{ required: true, message: "请选择出生日期" }]}
        >
          <DatePicker placeholder="请选择出生日期" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
      {submittedData && (
        <div>
          <h2>计算结果：</h2>
          <p>姓名: {submittedData.name}</p>
          <p>生肖：{submittedData.zodiac}</p>
          <p>
            你的五行：{submittedData.tianGan}
            {submittedData.fiveElements}
            {submittedData.gender}
          </p>
          <p>心动类型：{dataSet?.heartbeat}</p>
          <p>
            最佳婚配：
            {dataSet?.marriage?.map((item) => (
              <span key={item}>{item} </span>
            ))}
          </p>
          <p>正面性格： {dataSet?.positive}</p>
          <p>负面性格： {dataSet?.negative}</p>
          <p>健康建议： {dataSet?.suggestion}</p>
        </div>
      )}
    </div>
  );
};

export default App;
